import { Activity, IActivity } from '../models/Activity';
import mongoose from 'mongoose';
import { logger } from '../utils/logger';

export interface ActivityData {
  userId: string;
  type: IActivity['type'];
  target: string;
  targetId: string;
  targetTitle?: string;
  content?: string;
  metadata?: any;
}

export class ActivityService {
  /**
   * 记录用户活动
   */
  static async log(data: ActivityData): Promise<void> {
    try {
      const activity = new Activity({
        user: data.userId,
        type: data.type,
        target: data.target,
        targetId: data.targetId,
        targetTitle: data.targetTitle,
        content: data.content || this.generateContent(data),
        metadata: data.metadata
      });

      await activity.save();
      logger.info('活动记录已创建', { activity: activity._id, type: data.type });
    } catch (error) {
      logger.error('记录活动失败', { error, data });
      // 不抛出错误，避免影响主要业务流程
    }
  }

  /**
   * 生成活动描述
   */
  private static generateContent(data: ActivityData): string {
    const actionMap: Record<string, string> = {
      create: '创建了',
      update: '更新了',
      delete: '删除了',
      publish: '发布了',
      archive: '归档了',
      view: '查看了',
      like: '点赞了',
      comment: '评论了'
    };

    const targetMap: Record<string, string> = {
      lessonPlan: '教案',
      comment: '评论',
      user: '用户'
    };

    const action = actionMap[data.type] || data.type;
    const target = targetMap[data.target] || data.target;
    const title = data.targetTitle ? `《${data.targetTitle}》` : '';

    return `${action}${target}${title}`;
  }

  /**
   * 获取用户的活动记录
   */
  static async getUserActivities(
    userId: string,
    limit: number = 10,
    skip: number = 0
  ): Promise<IActivity[]> {
    try {
      const activities = await Activity.find({ user: userId })
        .sort({ createdAt: -1 })
        .limit(limit)
        .skip(skip)
        .populate('user', 'name avatar')
        .lean();

      return activities;
    } catch (error) {
      logger.error('获取用户活动记录失败', { error, userId });
      throw error;
    }
  }

  /**
   * 获取指定目标的活动记录
   */
  static async getTargetActivities(
    targetId: string,
    targetType?: string,
    limit: number = 10
  ): Promise<IActivity[]> {
    try {
      const query: any = { targetId };
      if (targetType) {
        query.target = targetType;
      }

      const activities = await Activity.find(query)
        .sort({ createdAt: -1 })
        .limit(limit)
        .populate('user', 'name avatar')
        .lean();

      return activities;
    } catch (error) {
      logger.error('获取目标活动记录失败', { error, targetId });
      throw error;
    }
  }

  /**
   * 批量记录活动
   */
  static async logBatch(activities: ActivityData[]): Promise<void> {
    try {
      const activityDocs = activities.map(data => ({
        user: data.userId,
        type: data.type,
        target: data.target,
        targetId: data.targetId,
        targetTitle: data.targetTitle,
        content: data.content || this.generateContent(data),
        metadata: data.metadata
      }));

      await Activity.insertMany(activityDocs);
      logger.info('批量活动记录已创建', { count: activities.length });
    } catch (error) {
      logger.error('批量记录活动失败', { error });
    }
  }

  /**
   * 清理旧的活动记录（保留最近30天）
   */
  static async cleanOldActivities(): Promise<void> {
    try {
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

      const result = await Activity.deleteMany({
        createdAt: { $lt: thirtyDaysAgo }
      });

      logger.info('清理旧活动记录完成', { deleted: result.deletedCount });
    } catch (error) {
      logger.error('清理旧活动记录失败', { error });
    }
  }
}